package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 套餐添加
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto){
        boolean flag = setmealService.add(setmealDto);
        if (flag){
        return R.success("套餐添加成功!");
        }else {
           return R.success("添加失败!");
        }
    }

    /**
     * 套餐分页
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Cacheable(value = "setmealCache",key = "#page+'_'+#pageSize")
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        Page<Setmeal> p = new Page<>(page,pageSize);
        Page<SetmealDto> dtoPage= new Page<>();
        LambdaQueryWrapper<Setmeal> lam = new LambdaQueryWrapper<>();
        lam.like(name !=null,Setmeal::getName,name);
        setmealService.page(p, lam);
        //将其他数据拷贝
        BeanUtils.copyProperties(p,dtoPage,"records");
        List<SetmealDto> collect = p.getRecords().stream().map((s)->{
            SetmealDto dto=new SetmealDto();
            String categoryName = categoryService.getById(s.getCategoryId()).getName();
            BeanUtils.copyProperties(s,dto);
            dto.setCategoryName(categoryName);
            return dto;
        }).collect(Collectors.toList());
        dtoPage.setRecords(collect);
        return R.success(dtoPage);
    }

    /**
     * 数据回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> show(@PathVariable Long id){
        //根据id获取套餐并将他拷贝到dto
        SetmealDto setmealDto = new SetmealDto();
        Setmeal byId = setmealService.getById(id);
        BeanUtils.copyProperties(byId,setmealDto);
        //根据id查询出套餐包含的菜品集合,并将它们存入dto对象
        LambdaQueryWrapper<SetmealDish> lam = new LambdaQueryWrapper<>();
        lam.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> list = setmealDishService.list(lam);
        setmealDto.setSetmealDishes(list);
        //返回dto
        return R.success(setmealDto);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @DeleteMapping
    public R<String> deleteByIds(Long[] ids){
        setmealService.deleteByIds(ids);
        return R.success("套餐删除成功");
    }

    /**
     * 批量修改套餐状态
     * @param statusId
     * @param ids
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @PostMapping("/status/{statusId}")
    public R<String> setStatus(@PathVariable int statusId,Long[] ids){
        for (Long id : ids) {
            Setmeal byId = setmealService.getById(id);
            byId.setStatus(statusId);
            setmealService.updateById(byId);
        }
        return R.success("套餐状态修改成功!");
    }

    /**
     * 套餐修改
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto){
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        LambdaQueryWrapper<SetmealDish> lam = new LambdaQueryWrapper<>();
        lam.eq(SetmealDish::getSetmealId,setmealDto.getId());
        //当setmealDish表里面有套餐数据时才进行删除
        List<SetmealDish> list = setmealDishService.list(lam);
        if (list!=null){
        setmealDishService.remove(lam);
        }
        //给每个菜品添加套餐id
        List<SetmealDish> collect = setmealDishes.stream().map(s -> {
            s.setSetmealId(setmealDto.getId());
            return s;
        }).collect(Collectors.toList());

        //当前端数据不为空时才进行添加
        if (setmealDishes!=null){
        setmealDishService.saveBatch(collect);
        }
        //修改套餐数据
        setmealService.updateById(setmealDto);
        return R.success("修改成功!");

    }

    /**
     * 根据条件查询套餐数据
     * @param setmeal
     * @return
     */
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(queryWrapper);
        return R.success(list);
    }


}
